package com.demo.security.authenticate.summary;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import com.demo.security.Base64Util;
import com.demo.security.MD5Util;
import com.demo.security.authenticate.Constant;

/**
 * 摘要认证客户端
 *
 * @author lee9213@163.com
 * @version 1.0
 * @date 2017/3/17 14:43
 */
public class Client {

    /**
     * 参数摘要生成
     * @param params
     * @return
     * @throws Exception
     */
    public static String getDigest(Map<String,String> params) throws Exception {
        Set<String> keySet = params.keySet();
        TreeSet<String> sortSet = new TreeSet<>();
        sortSet.addAll(keySet);
        StringBuilder keyValueStr = new StringBuilder();
        Iterator<String> iterator = sortSet.iterator();
        while(iterator.hasNext()){
            String key = iterator.next();
            String value = params.get(key);
            keyValueStr.append(key).append(value);
        }
        keyValueStr.append(Constant.SECRET);
        String base64Str = Base64Util.byte2base64(MD5Util.MD5(keyValueStr.toString()));
        return base64Str;
    }

    /**
     * 响应摘要验证
     * @param responseContent
     * @param digest
     * @return
     * @throws Exception
     */
    public static boolean validate(String responseContent,String digest) throws Exception {
        byte[] bytes = MD5Util.MD5(responseContent+ Constant.SECRET);
        String responseDigest = Base64Util.byte2base64(bytes);
        if(responseDigest.equals(digest)){
            return true;
        }
        return  false;
    }
}
